/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.www.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;

/**
 *
 * @author alex
 */
public class URLRetriever {

   URL url;
   
   public URLRetriever(URL url) {
      this.url = url;
   }
   
   public void retrieve(File output,String username,String password)
      throws IOException
   {
      URLConnection connection = url.openConnection();
      if (connection instanceof HttpsURLConnection) {
         HttpsURLConnection https = (HttpsURLConnection)connection;
         https.setHostnameVerifier(org.apache.commons.ssl.HostnameVerifier.DEFAULT_AND_LOCALHOST);
      }
      if (username!=null) {
         connection.setRequestProperty("Authorization", "Basic " + Base64Coder.encode(username+':'+password));
      }
      String charset = "UTF-8";
      InputStream is = connection.getInputStream();
      
      FileOutputStream os = new FileOutputStream(output);
      
      byte [] buffer = new byte[16384];
      int len;
      while ((len=is.read(buffer))>=0) {
         os.write(buffer,0,len);
      }
      is.close();
      os.close();
   }
}
